package com.kum.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.kum.domain.entity.LoginUser;
import com.kum.domain.entity.SysUserInfo;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;

public class JwtUtil {

    /**
     * 过期时间为一天
     * TODO 正式上线更换为15分钟
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "2333";

    /**
     * 生成签名,15分钟后过期
     *
     * @return
     */
    public static String sign(LoginUser loginUser) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        return JWT.create().withHeader(header).withClaim("loginUser", JSON.toJSONString(loginUser))
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean verity(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 获取token中载荷的数据
     * @param token
     * @return
     */
    public static LoginUser getPayload(String token) {
        try {
            if(!verity(token)){
                throw new  Exception();
            }
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String payload = jwt.getPayload();
            JSONObject object = (JSONObject) JSON.parse(Base64.getDecoder().decode(payload));
            return JSON.toJavaObject(object.getJSONObject("loginUser"),LoginUser.class);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {


        LoginUser payload = getPayload("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpblVzZXIiOiJ7XCJpZFwiOlwiMVwiLFwiaW5mb1wiOntcImlkXCI6XCJhYVwiLFwibmlja05hbWVcIjpcImFhYWFcIn0sXCJ1c2VyTmFtZVwiOlwiYWRtaW5cIn0iLCJleHAiOjE2MjI0NDc1NTl9.lc5-bkwjk_1bU5LeYtMLaZW7e5NYhSvdVgsCvUwV67w");
        System.out.println(payload);


    }


}